﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.Repository;
using WMS.FC.Domain.Service.System;
using WMS.FC.Domain.Service.Technology.Interface;

namespace WMS.FC.Domain.Service.Technology
{
    public class ChangeTrayTechnologyService : ServiceBase, IChangeTrayTechnologyService
    {
        protected readonly ITrayRepository trayRepository;
        protected readonly ITechnologyRepository technologyRepository;

        public ChangeTrayTechnologyService(
            ILogger<ServiceBase> logger,
            IOptions<WmsSettings> options,
            IMapper mapper,
            ITechnologyRepository technologyRepository,
            ITrayRepository trayRepository)
            : base(logger, options, mapper)
        {
            this.technologyRepository = technologyRepository;
            this.trayRepository = trayRepository;
        }

        public async Task<ActionResultBase> ChangeTrayTechnology(string trayBarcode, string technologyRouteCode, string technologyProcessCode, UserInfo userInfo)
        {
            var result = new ActionResultBase("变更托盘工艺");
            try
            {
                if (string.IsNullOrWhiteSpace(trayBarcode))
                    return result.ArgumentError("托盘条码不能为空");

                if (string.IsNullOrWhiteSpace(technologyRouteCode))
                    return result.ArgumentError("工艺路径不能为空");

                if (string.IsNullOrWhiteSpace(technologyProcessCode))
                    return result.ArgumentError("工艺工序不能为空");

                var trayPO = await trayRepository.GetTrayByBarcode(trayBarcode);
                if (trayPO == null)
                    return result.BusinessError($"托盘条码:{trayBarcode},未登录");

                var trayPOList = await trayRepository.GetTrayListByBarcode(trayPO.ContainerBarcode);
                var trayBarcodeList = trayPOList.Select(entity => entity.Barcode).ToList();

                var count = await technologyRepository.ChangeTrayListTechnology(trayBarcodeList, technologyRouteCode, technologyProcessCode, userInfo);
                if (count == 0)
                    return result.DbError("更新托盘工艺异常");

                count = await technologyRepository.ChangeCellListTechnology(trayBarcodeList, technologyRouteCode, technologyProcessCode, userInfo);
                if (count == 0)
                    return result.DbError("更新电池工艺异常");

                result.Message = "托盘变更工艺成功";
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }
    }
}
